package f3a.clockservice;

import java.util.ArrayList;

import android.R;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import f3a.bancohoras.TimeManager;
import f3a.bancohoraswidget.BancoHorasWidget;
import f3a.timermodule.WorkingTimeCounter;

public class ClockService extends Service{
	
	private static final String TAG = "MyService";
	 
	static final int refreshTime = 1000;
	private boolean runFlag = false;
	private boolean timerRunningFlag = false;
	private Updater refresher;
	//public Notification.Builder clockNotifierBuilder;
	public Notification clockNotifier;
	public NotificationManager clockNotifierManager;
	public PendingIntent workingTimeCounterPendingIntent;
	public TimeManager clockCounter;
	public Context context;
//	private final IBinder thisBinder = new LocalBinder();
	private BancoHorasWidget widget;
	
	ArrayList<Messenger> myClients = new ArrayList<Messenger>();
	int myValue = 0;
	public static final int MSG_REGISTER_CLIENT = 1;
	public static final int MSG_UNREGISTER_CLIENT = 2;
	public static final int MSG_SET_INT_VALUE = 3;
	public static final int MSG_SET_STRING_VALUE = 4;
	public static final int MSG_START_COUNTER = 5;
	public static final int MSG_PAUSE_COUNTER = 6;
	public static final int MSG_DELETE_COUNTER = 7;
	public static final int MSG_SET_TIMER_VALUE = 8;
    final Messenger myMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
    private int counter = 0, incrementby = 1;
    public static boolean isRunning = false;
	private static IBinder myBinder;
    
    
//	public class LocalBinder extends Binder {
//		public ClockService getService(){
//			return ClockService.this;
//		}
//	}
	
	@Override
    public IBinder onBind(Intent arg0) {
        myBinder = myMessenger.getBinder();
		return myBinder;
    }
	
	public static IBinder getClockBinder(){
		return myBinder;
	}
	
	@SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                myClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                myClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            case MSG_START_COUNTER:
            	clockCounter.start();
            	buildNotifier();
            	timerRunningFlag = true;
            	break;
            case MSG_PAUSE_COUNTER:
            	clockCounter.pause();
            	timerRunningFlag = false;
            	break;
            case MSG_DELETE_COUNTER:
            	clockCounter.delete();
            	timerRunningFlag = false;
            	break;
            case MSG_SET_TIMER_VALUE:
            	clockCounter.setClockTime((long) msg.arg1);
            	break;
            default:
                super.handleMessage(msg);
            }
        }
    }
 
	private void sendMessageToUI(int intvaluetosend) {
        for (int i=myClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                myClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
//                b.putString("str1", "ab" + intvaluetosend + "cd");
                b.putLong(TAG, clockCounter.getTime());
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                myClients.get(i).send(msg);

            } catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                myClients.remove(i);
            }
        }
    }
	
    @Override
    public void onCreate() {
        super.onCreate();
        
        this.refresher = new Updater();
        
//    	Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_SHORT).show();
//        Log.d(TAG, "onCreate");
        
        clockCounter = new TimeManager((long) (8*60+30)*60*1000, "seconds", "down", "HH:MM:SS");
        
        context = ClockService.this.getApplicationContext();
    	
    	clockNotifierManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    	
    	clockNotifier = new Notification();
    	
    	isRunning = true;
    	
//    	buildNotifier();
        
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        
        this.runFlag = true;
        this.refresher.start();
        
//    	Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
//        Log.d(TAG, "onStart");
        
        
//        clockCounter.start();
        
        return START_STICKY;
    //Note: You can start a new thread and use it for long background processing from here.
    }
 
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	
    	this.runFlag = false;
    	this.refresher.interrupt();
    	this.refresher = null;
    	this.isRunning = false;
    	
    	clockCounter.delete();
    	
    	clockNotifierManager.cancel(0);
    	
//        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_SHORT).show();
//        Log.d(TAG, "onDestroy");
    }

    public static boolean isRunning()
    {
        return isRunning;
    }

    @SuppressWarnings("deprecation")
	private void buildNotifier(){
    	clockNotifier.icon = android.R.drawable.stat_notify_sync;
    	clockNotifier.tickerText = "Teste";
    	clockNotifier.when = System.currentTimeMillis();
    	clockNotifier.flags |= Notification.FLAG_NO_CLEAR;
    	clockNotifier.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
    	
    	Intent notificationIntent = new Intent(context,WorkingTimeCounter.class);
        
//    	notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    	
    	workingTimeCounterPendingIntent = PendingIntent.getActivity(this.getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    	
    	clockNotifier.setLatestEventInfo(context, "Title", clockCounter.toString(), workingTimeCounterPendingIntent);
    	
    	clockNotifierManager.notify(0, clockNotifier);
    	
//    	Log.d(TAG,"Notifier Activated");
    }
    
    private class Updater extends Thread {
    	public Updater(){
    		super("ClockService-Clock");
    	}
    	
    	@Override
    	public void run() {
    		ClockService clockService = ClockService.this;
    		while (clockService.runFlag){
//    			Log.d(TAG, "Updater running");
    			
    			try {
//    				Log.d(TAG, "Updater ran");
    				Thread.sleep(refreshTime);
    				if (timerRunningFlag){
    					buildNotifier();
    				}
//    				widget.setWidgetText();
//    				counter += incrementby;
    				sendMessageToUI((int) clockCounter.getTime());
    				
    			} catch (InterruptedException e) {
    				clockService.runFlag = false;
    			}
    			
    		}
    		
    	}
    	
    }

}

